package org.example;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.Scanner;

public class GroupChat2 {
    private static final String NAMESRV_ADDR = "124.71.28.51:9876";
    private static final String GROUP_CHAT_TOPIC = "IM_TOPIC";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 启动生产者
        startProducer(scanner);

        // 启动消费者，每个用户一个消费者组
        String username = "user2"; // 从命令行参数获取用户名
        startConsumer(username);
    }

    private static void startProducer(Scanner scanner) {
        new Thread(() -> {
            try {
                DefaultMQProducer producer = new DefaultMQProducer("im_producer_group");
                producer.setNamesrvAddr(NAMESRV_ADDR);
                producer.start();

                while (true) {
                    System.out.print("Enter your message: ");
                    String message = scanner.nextLine();

                    // 发送消息到群聊Topic
                    Message msg = new Message(GROUP_CHAT_TOPIC, "TAG_A", message.getBytes());
                    producer.send(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void startConsumer(String username) {
        new Thread(() -> {
            try {
                DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("im_consumer_group_" + username);
                consumer.setNamesrvAddr(NAMESRV_ADDR);
                consumer.subscribe(GROUP_CHAT_TOPIC, "TAG_A");

                // 注册消息处理器
                consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
                    for (MessageExt msg : msgs) {
                        // 处理收到的消息
                        System.out.println(new String(msg.getBody()));
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                });

                consumer.start();

                System.out.println("Group Chat Consumer Started for user: " + username);

                // 保持消费者线程一直运行，监听消息
                while (true) {
                    // 睡眠一段时间，防止过于频繁的轮询
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
